package cn.anline.www.dao;

import cn.anline.www.bean.BlogBean;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BlogDao extends JdbcDaoSupport {
    public List<BlogBean> findAll(){
        List<BlogBean> list = new ArrayList<BlogBean>();
        String sql = "SELECT * FROM blog";
        list = getJdbcTemplate().query(sql, new RowMapper<BlogBean>(){
            @Override
            public BlogBean mapRow(ResultSet resultSet, int i) throws SQLException {
                BlogBean blogBean = new BlogBean();
                blogBean.setId(resultSet.getInt("id"));
                blogBean.setUid(resultSet.getInt("uid"));
                blogBean.setTitle(resultSet.getString("title"));
                blogBean.setDescription(resultSet.getString("description"));
                blogBean.setContent(resultSet.getString("content"));
                return blogBean;
            }
        });
        return list;
    }

    public void addNew(BlogBean blogBean){
        String sql="insert into blog(title,description,content) values(?,?,?)";
        getJdbcTemplate().update(sql, new Object[]{blogBean.getTitle(),blogBean.getDescription(),blogBean.getContent()});
        return ;
    }

    public List<BlogBean> findById(int id){
        String sql = "SELECT * FROM `blog` WHERE id = ?";
        List<BlogBean> list = getJdbcTemplate().query(sql,new Object[]{id},new RowMapper<BlogBean>(){

            @Override
            public BlogBean mapRow(ResultSet resultSet, int i) throws SQLException {
                BlogBean blogBean = new BlogBean();
                blogBean.setId(resultSet.getInt("id"));
                blogBean.setUid(resultSet.getInt("uid"));
                blogBean.setTitle(resultSet.getString("title"));
                blogBean.setDescription(resultSet.getString("description"));
                blogBean.setContent(resultSet.getString("content"));
                return blogBean;
            }
        });
        return list;
    }
}
